<template>
  <div style="border: 1px solid #ccc">
    <Toolbar
      style="border-bottom: 1px solid #ccc"
      :editor="editorRef"
      :defaultConfig="toolbarConfig"
      :mode="mode"
    />
    <Editor
      v-bind="attrs"
      style="height: 300px; overflow-y: hidden"
      :defaultConfig="editorConfig"
      :mode="mode"
      @onCreated="handleCreated"
    />
  </div>
</template>
<script setup>
import '@wangeditor/editor/dist/css/style.css' // 引入 css
import { onBeforeUnmount, ref, shallowRef, onMounted } from 'vue'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import { getAccessToken } from '@/utils/auth'
const attrs = useAttrs()
const editorRef = shallowRef()
const props = defineProps({
  placeholder:String
})
const mode = ref('default')

onMounted(() => {
  
})

const toolbarConfig = {}
const editorConfig = { placeholder: props.placeholder,MENU_CONF:{} }
editorConfig.MENU_CONF['uploadImage'] = {
  server: import.meta.env.VITE_BASE_URL + import.meta.env.VITE_API_URL + '/infra/file/upload',
  allowedFileTypes: [],
  fieldName: 'file',
  headers: {
    Authorization: 'Bearer ' + getAccessToken(),
  },
  customInsert(res, insertFn) {
    // TS 语法
    // customInsert(res, insertFn) {                  // JS 语法
    // res 即服务端的返回结果

    // 从 res 中找到 url alt href ，然后插入图片
    console.log(res.data);
    const url = res.data
    insertFn(url)
  },
}
// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value
  if (editor == null) return
  editor.destroy()
})

const handleCreated = (editor) => {
  editorRef.value = editor // 记录 editor 实例，重要！
}
</script>
